package com.lechi.web.runner;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.lechi.web.common.alarm.AlarmRuleFactory;
import com.lechi.web.common.alarm.AlarmRuleStrategy;
import com.lechi.web.common.config.LeChiConfig;
import com.lechi.web.dto.IotAlarmThresholdDto;
import com.lechi.web.framework.util.GuavaCacheUtil;
import com.lechi.web.service.IIotDeviceCmdService;
import com.lechi.web.service.IIotTriggerRulesService;
import com.lechi.web.system.domain.IotDeviceCmdParse;
import com.lechi.web.system.domain.IotTriggerRulesParse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 项目启动后缓存传感器告警规则
 */
@Slf4j
@Component("CacheAlarmRules")
@Order(5)
public class CacheAlarmRules implements CommandLineRunner {

    @Autowired
    private IIotDeviceCmdService iotDeviceCmdService;

    @Autowired
    private IIotTriggerRulesService iotTriggerRulesService;

    @Autowired
    private LeChiConfig leChiConfig;

    public void run(String... args) {
        if ("DaPeng".equals(leChiConfig.getName())) {
            return;
        }

        Long deviceId = args != null && args.length != 0 ? Long.parseLong(args[0]) : null;
        List<IotDeviceCmdParse> iotDeviceCmdCreateList = iotDeviceCmdService.selectIotDeviceCmdListByOrder(deviceId);
        List<IotTriggerRulesParse> iotTriggerRulesList = iotTriggerRulesService.selectIotTriggerRulesForCache(deviceId);
        iotDeviceCmdCreateList.forEach(iotDeviceCmdCreate -> {
            var deviceSensorKey = iotDeviceCmdCreate.getDeviceId() + "_" + iotDeviceCmdCreate.getSensorAliasId();
            iotTriggerRulesList.stream().filter(iotTriggerRules -> Objects.equals(deviceSensorKey, iotTriggerRules.getDeviceId() + "_" + iotTriggerRules.getSensorAliasId()))
                    .forEach(iotTriggerRules -> {
                        JSONArray jsonArray = JSONUtil.parseArray(iotTriggerRules.getRuleContext()); // 一个要素下有一组告警规则
                        List<IotAlarmThresholdDto> iotAlarmThresholdDtoList = JSONUtil.toList(jsonArray, IotAlarmThresholdDto.class);
                        List<AlarmRuleStrategy> alarmRuleStrategyList = Lists.newArrayList();
                        iotAlarmThresholdDtoList.forEach(alarmThresholdDto -> {
                            AlarmRuleStrategy alarmRuleStrategy = AlarmRuleFactory.getAlarmRuleStrategy(alarmThresholdDto.getAlarmType());
                            if (alarmRuleStrategy == null) {
                                log.error("告警类型：{} 获取告警策略为空！", alarmThresholdDto.getAlarmType());
                                return;
                            }
                            BeanUtils.copyProperties(alarmThresholdDto, alarmRuleStrategy);
                            alarmRuleStrategy.setSensorAliasId(iotDeviceCmdCreate.getSensorAliasId());
                            alarmRuleStrategyList.add(alarmRuleStrategy);

                        });
                        var alarmRuleKey = "AlarmRule_Id_" + iotDeviceCmdCreate.getDeviceId() + "_" + iotDeviceCmdCreate.getSensorAliasId();
                        GuavaCacheUtil.getAlarmRuleMap().put(alarmRuleKey, alarmRuleStrategyList);
                    });
        });
    }
}

